
function getLw(liId, lid) {
	get("lwDetail", {id : lid}, false, function (resp) {
		if(!resp || resp.code == 1) {
			showLayer(TEXT.NO_LW);
			return;
		}
		var btns = ['确认处理', '关闭'];
		if(!vl(liId)) {
			btns = ['关闭'];
		}
		var area = ['70%'];
		if(jianyueMobileClient()) {
			area = ['100%'];
		}
		
		var lwContent = "";
		lwContent = lwContent  + "<div class='satisfy-item'><span class='form-label-50'>渠道：" + resp.channel + "</span><span class='form-label-50'>姓名：" + resp.name + "</span></div>";
		lwContent = lwContent  + "<div class='satisfy-item'><span class='form-label-50'>手机：" + resp.phone + "</span><span class='form-label-50'>QQ：" + resp.qq + "</span></div>";
		lwContent = lwContent  + "<div class='satisfy-item'><span class='form-label-50' style='width:100%'>邮箱：" + resp.email + "</span></div>";
		lwContent = lwContent  + "<div class='satisfy-item'>" + resp.memo + "</div>";
		if(resp.status == "Y") {
			lwContent = lwContent  + "<div class='satisfy-item'>处理时间：" + getLocalTime(resp.handleTime) + "[" + resp.handleUser + "]</div>";
			lwContent = lwContent  + "<div class='satisfy-item'>处理意见：" + resp.handleResult + "</div>";
		} else if(agentSelfInfo != null){
			lwContent = lwContent  + "<div class='satisfy-item'>处理意见*：<textarea id='handleResult' style='width:95%;height:50px'></textarea></div>";
		}
		layer.open({
			type : 1,
			closeBtn : 1,
			title : "留言详情[" + TEXT["LW_" + resp.status] + "]",
			content : lwContent,
			move : false,
			area : area,
			shadeClose : true,
			maxmin : true,
			cancel: function(){ 
			    //右上角关闭回调
			    layer.closeAll();
			    return false;
			},
			btn: btns,
			yes: function(index, layero){
				if(btns.length == 2) {//存在两个按钮则处理‘确认处理’
					if($("#handleResult").val() == "") {
						showLayer(TEXT.INPUT_FULL_INFO);
					} else {
						if(handleLw(lid) == true) {
							$("#" + liId).prependTo($("#handledUL"));
							$("#" + liId).attr("id", liId.replace("M_", "L_"));
							$("#noHandledCount").html("[" + $("#noHandledUL li").length + "]");
							$("#handledCount").html("[" + $("#handledUL li").length + "]");
							layer.close(index);
							showLayer(TEXT.DO_SUCCESS);
						} else {
							showLayer(TEXT.DO_ERROR);
						}
					}
				} else {//仅存在一个按钮，则处理‘关闭’按钮
					layer.close(index);
				}
			},
			btn2: function(index, layero){//‘关闭’按钮，直接关闭
			}
		});
	});
}

function getNotifyTip(id, sid, time, text) {
	time = time.substring(0, 19);
	return '<div id="notify' + id + '" class="moreMessageDiv"><div class="notifyClass" title="' + sid + '">' + time + ' &nbsp' + text + '</div></div>';
}

function adapterSize(json, width, height) {
	if(json.width && json.height) {
		if(json.width > json.height) {
			if(json.width > width) {
				width = width;
			} else {
				width = json.width; 
			}
			height =  json.height * (width / json.width);
		} else {
			if(json.height > height) {
				height = height;
			} else {
				height = json.height; 
			}
			width =  json.width * (height / json.height);
		}
	}
	var myArray=new Array();
	myArray[0] = width;
	myArray[1] = height;
	return myArray;
}

function getImageDiv(json) {
	var showname = json.oldName;
	var name = json.newName;
	var size = json.size/1024;
	var overdue = json.overdue;
	var date = json.date;
	
	var pid0 = "";
	if(agentSelfInfo) {//坐席侧
		pid0 = talkingVisitor[currentVisitorId].object.session.pid;
	} else {//访客侧
		pid0 = pid;
	}
	var url = MSG_FILE_PATH + date + "/" + name + "&pid=" + pid0;
	var v =  "";
	v = v + '<div>';
	//var width = 300;
	//var height = 300;
	var arr = adapterSize(json, SHOW_PIC.w, SHOW_PIC.h);
	var width = arr[0];
	var height = arr[1];
	
	v = v + '	<a href="' + url + '" target="_blank"><image src="' + url + '" width="' + width + 'px", height="' + height + 'px"></a>';
	v = v + '</div>';
	return v;
}
function getFileDiv(json) {
	var showname = json.oldName;
	var name = json.newName;
	var size = json.size/1024;
	var overdue = json.overdue;
	var date = json.date;
	var pid0 = "";
	if(agentSelfInfo) {//坐席侧
		pid0 = talkingVisitor[currentVisitorId].object.session.pid;
	} else {//访客侧
		pid0 = pid;
	}
	
	var extStart = name.lastIndexOf(".");
 	var ext = name.substring(extStart, name.length).toUpperCase();
	if(ext == ".BMP" ||ext == ".PNG" || ext  ==  ".GIF" || ext  ==  ".JPG" || ext  ==  ".JPEG") {
		return getImageDiv(json);
	}
	size = Math.ceil(size);
	var v = "";
	v = v + '<div class="sendIn" id="senSucc">';
	v = v + '    <img src="../themes/online/file.png" class="file-img">';
	v = v + '        <p class="tit">';
	v = v + '            <span>' + showname + '</span>';
	v = v + '            <em>' + size + 'KB</em>';
	v = v + '        </p>';
	v = v + '        <div class="sendDown fr">' + overdue + '&#160;';
	var fn = MSG_FILE_PATH + date + "/" + name + "&name=" + showname + "&pid=" + pid0;
	v = v + '        <a href="' + fn + '" download="" target="_blank">';
	v = v + '            <img src="../themes/online/down.png" class="fl"></img>';
	v = v + '        </a></div>';
	v = v + '    </img>';
	v = v + '</div>';
	return v;
}

function getOrderDiv(json) {
	var v = "";
	v = v + '<div class="sendIn" id="senSucc">';
	v = v + '    <img src="' + json.imgUrl + '" class="file-img" width="50px" height="50px">';
	v = v + '        <p class="tit">';
	v = v + '            <span>' + json.title + '</span>';
	v = v + '            <em>￥' + json.price + 'KB</em>';
	v = v + '            <br/><span style="white-space: normal">' + json.desc + '</span>';
	v = v + '            <br/><span>' + json.time;
	if(vl(json.href)) {
		v = v + '			<a href="' + json.href + '" target="_blank">' + TEXT.VIEW + ' </a>';
	}
	v = v + '			</span>';
	v = v + '        </p>';
	v = v + '    </img>';
	v = v + '</div>';
	return v;
}

function getMapDiv(json) {
	var v = "";
	v = v + '<div class="sendIn" id="senSucc">';
	v = v + '    地图信息：' + json.address + "，<a href='javascript:toShowMap(" + json.lng + ", " + json.lat + ")'>点击查看</a>";
	v = v + '</div>';
	return v;
}

function showChatMessge(amessage, prepend) {
	var v = "";
	if(amessage.event == MESSAGE_EVENT.CHAT) {//聊天会话的内容
		var bubbleOrNo = "bubble";
		//根据不同的消息类型，决定不同inner显示
		var inner = "";
		if(amessage.multiType == MULIT_TYPE.FILE) {//文件
			try {
				var json = JSON.parse(amessage.value ? amessage.value : amessage.text);
				inner = getFileDiv(json);
			} catch(e){
				return;
			}
			bubbleOrNo = "bubble2";
		} else if(amessage.multiType == MULIT_TYPE.ORDER) {//订单消息
			//inner = "这是订单格式，要格式化";
			try {
				var json = JSON.parse(amessage.value ? amessage.value : amessage.text);
				inner = getOrderDiv(json);
			} catch(e){
				return;
			}
		} else if(amessage.multiType == MULIT_TYPE.MAP) {//地图信息
			try {
				var json = JSON.parse(amessage.value ? amessage.value : amessage.text);
				inner = getMapDiv(json);
			} catch(e){
				return;
			}
		} else if(amessage.multiType == MULIT_TYPE.AUDIO) {//语音消息
			try {
				var pid0 = "";
				if(agentSelfInfo) {//坐席侧
					pid0 = talkingVisitor[currentVisitorId].object.session.pid;
				} else {//访客侧
					pid0 = pid;
				}
				var json = JSON.parse(amessage.value ? amessage.value : amessage.text);
				var fn = MSG_FILE_PATH + json.date + "/" + json.newName + "&name=录音" + json.newName + "&pid=" + pid0;
				inner = "这是语音文件，要格式化";
				var tmp = "";
				tmp = tmp + '<div class="autioCon">';
				var fc = "playAmr('" + fn + "', '" + amessage.id + "', " + json.duration + ")";
				tmp = tmp + '  <a id="audio-play-' + amessage.id + '" href="javascript:' + fc + ';" class="autioBtnPlay" onclick=""/>';
				tmp = tmp + '  <p><span style="width:0%;" id="progress-' + amessage.id + '"/></p>';
				tmp = tmp + '  <em>' + json.duration + 's</em>';
				tmp = tmp + '  <a href="' + fn + '" class="autioDown"/>';
				tmp = tmp + '</div>';
				inner = tmp;
			} catch(e) {
			}		
		} else {//普通文本
			inner = amessage.value ? amessage.value : amessage.text;
		}
			
		var hide = '';
		if(hideName == true) {
			hide = 'style="display:none"';
		}
		var left;
		var isAgentSend = amessage.senderRole == SENDER_ROLE.SYSTEM || amessage.senderRole == SENDER_ROLE.AGENT || amessage.senderRole == SENDER_ROLE.MANAGER;
		if(isAgentSend) {
			if(!agentSelfInfo) {
				left = true;
			} else {
				left = false;
			}
		} else {
			if(!agentSelfInfo) {
				left = false;
			} else {
				left = true;
			}
		}
		if(left) {
			v = v + '<div class="msg-agent">';
			v = v + ' 	<div class="name" ' + hide + '>' + amessage.senderNickname + '&nbsp;&nbsp;<span id="Time' + amessage.id + '">' + amessage.time + '</span></div>';
			v = v + ' 	<div id="' + amessage.id + '" class="' + bubbleOrNo + '">';
			v = v + ' 		<span class="arrow"></span>';
			v = v + ' 		<div id="inner-' + amessage.id + '" onmouseover="showFunction(\'' + amessage.id + '\')">' + inner + '</div>';
			v = v + ' 	</div>';
			if(agentSelfInfo) {//坐席
				v = v + '<div title="点击查询快捷回复" style="font-size:11px;cursor:pointer;display:none" onclick="searchFAQ(\'' + amessage.id + '\')" id="function_' + amessage.id + '" title="直接搜索快捷提问的内容">[搜索FAQ]</div>';
			}
			v = v + '</div>';
		} else {
			var nk = amessage.senderNickname ? amessage.senderNickname  : TEXT.ME;
			v = v + '<div class="msg-client">';
			v = v + ' 	<div class="name" ' + hide + '>' + nk + '&nbsp;&nbsp;';
			v = v + '		<span id="Time' + amessage.id + '">' + amessage.time + '</span>';
			v = v + ' 		<span style="cursor:pointer;display:none" onclick="useThis(\'' + amessage.id  + '\')" id="function_' + amessage.id + '" title="将消息填入输入框方便再次编辑发送">[编辑]</span>';
			v = v +' 	</div>';
			v = v + ' 	<div id="' + amessage.id + '" class="' + bubbleOrNo + '">';
			v = v + ' 		<span class="arrow"></span>';
			v = v + ' 		<div id="inner-' + amessage.id + '" onmouseover="showFunction(\'' + amessage.id + '\')">' + inner + '</div>';
			v = v + ' 	</div>';
			v = v + '</div>';		
		}
	} else {//操作\留言\归档等动作
		var text = ARCHIVE_EVENT_TEXT[amessage.event];
		if(amessage.event == ARCHIVE_EVENT.AG_INVITE_AGENT || amessage.event == ARCHIVE_EVENT.AG_TRANSFER2_AGENT) {//邀请某个坐席
			text = "[" + amessage.senderNickname + "]" + text + "[" + amessage.text + "]";
		} else if(amessage.event == ARCHIVE_EVENT.AG_REJECT_INVITE || amessage.event == ARCHIVE_EVENT.AG_ACCEPT_INVITE || amessage.event == ARCHIVE_EVENT.AG_END_INVITE) {//某个坐席拒接邀请
			text = "[" + amessage.senderNickname + "]" + text;
		} else if(amessage.event == ARCHIVE_EVENT.ENTER_GROUP) {
			var g = vl(amessage.object) ? "[" + amessage.object + "]" : "";
			text = text + g;
		} else if(amessage.event == ARCHIVE_EVENT.ENTER_GROUP_RESULT) {
			var result = ENTER_GROUP_RESULT[amessage.text];
			var g = vl(amessage.text) ? "[" + result + "]" : "";
			text = text + g;
		} else if(amessage.event == ARCHIVE_EVENT.LW) {
			var clk = "[<a href='javascript:getLw(null, \"" + amessage.id + "\")'>" + TEXT.LW_DETAIL + "</a>]";
			text = text + clk;
		}
		if(!vl(text)) {
			text = ARCHIVE_EVENT.OTHER + "--" + amessage.event;
		}
		v = getNotifyTip(amessage.id, amessage.sid, amessage.time, text);
	}
	if("prepend" == prepend) {
		$("#msgHolder").prepend(v);
	} else {
		$("#msgHolder").append(v);
	}
}

function showFunction(id) {
	$("#function_" + id).show();
}

function searchFAQ(id) {
	showRightDiv(2);
	document.getElementById('faqFrame').contentWindow.searchFAQ($("#inner-" + id).html());
}

function useThis(id) {
	keditor.html(keditor.html() + $("#inner-" + id).html());
}

function showMoreMessage(pid) {
	$("#moreMessageDiv").remove();
	var v = '<div id="moreMessageDiv" class="moreMessageDiv"><a class="moreMessageHref" onclick="getLog(\'' + pid + '\', true)">' + TEXT.MORE + '</a></div>';
	$("#msgHolder").prepend(v);
}

function hideMoreMessage() {
	$("#moreMessageDiv").remove();
	var v = '<div id="moreMessageDiv" class="moreMessageDiv">' + TEXT.NO_MORE + '</div>';
	$("#msgHolder").prepend(v);
}


function toBottom() {
	$("#msgWrapper").getNiceScroll().resize();
    var divobj = $('#msgWrapper')[0];
    divobj.scrollTop = divobj.scrollHeight;
}


function sendChatMessage() {
	var textCount = vl(keditor) ? keditor.count("text") : $("#textarea").val().length;
	if (textCount == 0) {
		showLayer(TEXT.PLEASE_INPUT_MESSAGE);
		return;
	}
	if (textCount > 500) {
		showLayer(TEXT.INPUT_MSG_LIMIT);
		return;
	}
	var content = vl(keditor) ? keditor.html() : $("#textarea").val();
	content = content.replace("<p>", "");
	content = content.replace("</p>", "");
	content = $.trim(content);
	if (content != "" && $.trim(content) != "") {
		var sendContent = "";
		if (true) {
			sendContent = content;
		} else {
			var tempContent = $("<img>" + content + "<img>");
			for (var i = 1; i < tempContent.length - 1; i++) {
				if (tempContent[i].nodeName == "IMG") {
					sendContent = sendContent + tempContent[i].alt;
				} else {
					if (tempContent[i].nodeName == "BR") {
					} else {
						if (tempContent[i].nodeName == "P" && tempContent[i].firstElementChild && tempContent[i].firstElementChild.nodeName == "BR") {
							sendContent = sendContent + "\n";
						} else {
							if (tempContent[i]) {
								if (tempContent[i].textContent) {
									sendContent = sendContent + tempContent[i].textContent;
								} else {
									if (tempContent[i].data) {
										sendContent = sendContent + tempContent[i].data;
									} else {
										if (tempContent[i].innerHTML) {
											sendContent = sendContent + tempContent[i].innerHTML;
										}
									}
								}
							}
						}
					}
				}
			}
		}
		doSend(sendContent);
		setTimeout("editorEmpty()", 5);
	} else { // ȫΪ�ո�������
		$("#textarea").html(content.replace(/(\r\n|\n|\r)/gm, "")); // ȥ���з�
	}
}



function editorEmpty() {
	vl(keditor) ? keditor.html("") : $("#textarea").val("");
}


var alertTimeout = "";
function showTip(text, noHideTime) {
	if(vl(alertTimeout)) {
		clearTimeout(alertTimeout);
	}
	$("#alertInside").html(text);
	$("#alerting").show();	
	if(!vl(noHideTime)) {	
		alertTimeout = setTimeout('hideTip()', 3000);
	}
}


function hideTip() {
	$("#alertInside").html("");
	$("#alerting").hide();	
	if(vl(alertTimeout)) {
		clearTimeout(alertTimeout);
	}
}

function showLayer(text, time0) {
	var time = 4000;
	if(time0) {
		time = time0
	}
	layer.msg(text, {time: time});	
}


function toggleName() {
	if(hideName == true) {//��ǰ��������
		hideName = false;
		$(".name").show();
	} else {
		$(".name").hide();
		hideName = true;
	}
	$("#msgWrapper").getNiceScroll().resize();
	toBottom();	
}


function blockInput(tips, action) {
	if(action) {
		tips = "<span onclick='javascript:" + action + "' style='cursor:pointer'>" + tips + "</span>";
	}
	$('#footer').block({
			message:tips,
			overlayCSS:{
				opacity : 0.6,
				backgroundColor:'#FFF',
				'z-index':'98'
			},
			css : {
				border : 'none',
				width: '90%',
				padding : '0 20px',
				height:'26px',
				lineHeight:'26px',
				backgroundColor : '#FFF4CB',
				'-webkit-border-radius' : '10px',
				'-moz-border-radius' : '10px',
				opacity : 0.9,
				color : '#FE8045',
				fontSize:'12px',
				borderRadius:'13px'
			}
	});
}

function unBlockInput() {
	$('#footer').unblock();
}


function toShowMap(lng, lat) {
	var url = "../online/map.html";
	if(lng && lat) {
		url = url + "?lng=" + lng + "&lat=" + lat; 
	}
	layer.open({
		type : 2,
		closeBtn : 1,
		title : TEXT.MAP,
		content : url,
		move : false,
		area : [ "600px", "550px" ],
		shadeClose : true,
		maxmin : true,
		cancel: function(){ 
		    layer.closeAll();
		}
	});
}

///////////////////////////////////////////
var originalTitle = "";
var step=0;
var flash_title_timer;
function flashTitle(top) {
  if(window.opener || agentSelfInfo || top) {//弹窗的访客端或者是坐席端，都采用闪缩的方式提示
	  if(!flash_title_timer) {
	  	originalTitle = parent.document.title;
	  	flash_title_timer = setInterval(function () {
			flashTitle(top);
		}, 800);
	  }
		
	  step++;
	  if (step==3) { step=1 } 
	  if (step==1) { parent.document.title='[' + TEXT.HAVE_NEW_MESSAGE + ']' }
	  if (step==2) { parent.document.title='[' + TEXT.AGENT_SERVICE + ']' }
  }
}
function stopFalshTitle() {
	if(flash_title_timer) {
		clearTimeout(flash_title_timer);
		parent.document.title = originalTitle;
		flash_title_timer = null;
	}
}

window.onmouseover = function () {
	stopFalshTitle();
}

function showNotify(msg) {
	if(!msg) {
		msg = TEXT.HAVE_NEW_MESSAGE;
	}
	var title = TEXT.AGENT_SERVICE;
	var icon='../themes/online/notify.png';  
	var Notification = window.Notification || window.mozNotification || window.webkitNotification;

	if (Notification && Notification.permission === "granted") {
		var notificationInstance = new Notification(title, {
			body : msg,
			icon : icon,
			tag : 'agent'
		});
		notificationInstance.onclick = function() {
			//可直接打开通知notification相关联的tab窗口
		    window.focus();
		};
		notificationInstance.onerror = function() {
		};
		
		notificationInstance.onshow = function() {
		};
		
		notificationInstance.onclose = function() {
		};
		
	} else if (Notification && Notification.permission !== "denied") {
		Notification.requestPermission(function(status) {
			if (Notification.permission !== status) {
				Notification.permission = status;
			}
			// If the user said okay
			if (status === "granted") {
				var notificationInstance = new Notification(title, {
					body : msg,
					icon : icon,
					tag : 'agent' // 只弹一个框
				});
				
				notificationInstance.onclick = function() {
					//可直接打开通知notification相关联的tab窗口
				    window.focus();
				};
				notificationInstance.onerror = function() {
				};
				notificationInstance.onshow = function() {
				};
				notificationInstance.onclose = function() {
				};

			} else {
				return false
			}
		});
	} else {
		return false;
	}
}